﻿using DocumentFormat.OpenXml.Spreadsheet;
using ICSharpCode.SharpZipLib.Zip;
using Learun.Application.Base.SystemModule;
using Learun.Application.TwoDevelopment.ZZDT_EC;
using Learun.Util;
using Microsoft.Owin;
using NPOI.Util;
using System;
using System.IO;
using System.Web;
using System.Web.Http;
using System.Web.Http.Results;
using static Learun.Application.TwoDevelopment.ZZDT_EC.ec_library_fileBLL;

namespace Learun.Application.Web.AppApi
{
    /// <summary>
    /// 客户端更新接口，包括下载和上传（管理员）
    /// </summary>
    [RoutePrefix("api/UpdateApi")]
    [HandlerApiLogin(FilterMode.Ignore)]
    public class UpdateApiController : WebApiControllerBase
    {
        /// <summary>
        /// 下载自动化平台的更新程序
        /// </summary>
        /// <param name="MD5"></param>
        /// <param name="pkgName">Exe-X64</param>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult UpdateFile(string MD5, string pkgName = "Exe-X64")
        {
            try
            {
                pkgName += ".zip";
                string ServerPath = Config.GetValue("SWSUpdateFile");
                if (System.IO.Directory.Exists(ServerPath))
                {
                    string path = Path.Combine(ServerPath, pkgName);
                    if (FileDownHelper.FileExists(path))
                    {
                        var newMD5 = Md5Helper.Encrypt(File.ReadAllBytes(path), 32);
                        if (MD5 != newMD5)
                        {
                            FileDownHelper.DownLoadnew(path);
                            return Success("正在下载");
                        }
                        else
                        {
                            return Success("无需更新");
                        }
                    }
                    else
                    {
                        return BadRequest($"更新文件{path.Substring(2)}在服务器中不存在");//400的code
                    }
                }
                return BadRequest("更新文件夹在服务器中不存在");
            }
            catch (Exception ex)
            {
                return Fail("其他错误。" + ex.Message);
            }
        }

        /// <summary>
        /// 上传自动化平台的更新程序
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [SwaggerFileLoadAttr]
        public IHttpActionResult UploadFile(string adminPwd)
        {
            string exeName = "SignalManage";
            try
            {
                if (adminPwd != "CADTeam8081")
                {
                    return Fail("adminPwd参数（密码）不对");
                }
                else
                {
                    var x = HttpContext.Current.Request.Files;//HttpPostedFile file = HttpContext.Current.Request.Files["file"];//接收
                    if (x == null || x.Count == 0)
                    {
                        return Fail("未选择文件");
                    }
                    else
                    {
                        var file = x[0];
                        string fileName = Path.GetFileName(file.FileName);//文件名，带后缀名
                        if (!fileName.ToLower().EndsWith(".zip"))
                        {
                            return Fail("请上传zip格式的更新包。");
                        }
                        else
                        {
                            Stream s = file.InputStream;//文件流
                            #region 检查zip
                            bool foundExe = false;
                            //一个ZIP文件中的条目，可以理解为压缩包里面的一个文件夹/文件
                            ZipEntry theEntry = null;
                            //解压缩输出流，从压缩包中一个接一个的读出文档。
                            using (ZipInputStream inputStream = new ZipInputStream(s))
                            {
                                while ((theEntry = inputStream.GetNextEntry()) != null)
                                {
                                    if (theEntry.IsDirectory)
                                    {
                                    }
                                    else
                                    {
                                        if (theEntry.Name.ToLower() == exeName.ToLower() + ".exe")
                                        {
                                            foundExe = true;
                                        }
                                    }
                                }
                                inputStream.Close();
                            }
                            if (!foundExe)
                            {
                                return Fail($"未在zip中找到{exeName}.exe");
                            }
                            #endregion
                            int fileSize = file.ContentLength;
                            string ServerPath = Config.GetValue("SWSUpdateFile");
                            if (!System.IO.File.Exists(ServerPath))
                            {
                                Directory.CreateDirectory(ServerPath); //创建文件夹
                            }
                            using (var fileStream = File.Create(Path.Combine(ServerPath, fileName)))
                            {
                                s.Seek(0, SeekOrigin.Begin);
                                s.CopyTo(fileStream);
                            }
                        }
                    }
                }
                return Success("上传成功。");
            }
            catch (Exception ex)
            {
                return Fail("上传更新包错误。" + ex.Message);
            }
        }

        /// <summary>
        /// 下载插件端更新程序
        /// </summary>
        /// <param name="MD5">当前程序MD5</param>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult UpdateCAD(string MD5)
        {
            var folder = "StartCAD.zip";
            try
            {
                string ServerPath = Config.GetValue("SWSUpdateFile");
                if (System.IO.Directory.Exists(ServerPath))
                {
                    string path = Path.Combine(ServerPath, folder);
                    if (FileDownHelper.FileExists(path))
                    {
                        var newMD5 = Md5Helper.Encrypt(File.ReadAllBytes(path), 32);
                        if (MD5 != newMD5)
                        {
                            FileDownHelper.DownLoadnew(path);
                            return Success("正在下载");
                        }
                        else
                        {
                            return Success("无需更新");
                        }
                    }
                    else
                    {
                        return BadRequest($"更新文件{path.Substring(2)}在服务器中不存在");//400的code
                    }
                }
                return BadRequest($"更新文件夹在服务器中不存在");
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
    }
}